import json
import os
import uuid
from utils.randomUtils import generate_random_from_username_password

class UserDBManager:
    def __init__(self, users_db='./db/data/users_data.json'):
        self.users = {}
        self.users_db = users_db
        with open(users_db, 'r') as f:
            self.users = json.load(f)    

    
    def register(self, username, user_email, user_password)-> bool:
        user_id = generate_random_from_username_password(username, user_password)
        if user_id in self.users:
            return None
        self.users[user_id] = {
            'username': username,
            'user_email': user_email,
            'user_password': user_password,
            'user_projects': {}
        }
        try:
            with open(f'./db/data/users/{user_id}.json', 'w') as f:
                json.dump({}, f)
            with open(self.users_db, 'w') as f:
                json.dump(self.users, f)
        except Exception as e:
            print(e)
            return None
        return user_id
    
    def login(self, username, password):
        for user_id, user in self.users.items():
            if user['username'] == username and user['user_password'] == password:
                return user_id
        return None

    def get_user_login_info(self, user_id):
        return self.users.get(user_id, None)
    
    def get_user_projects(self, user_id):
        projects = {}
        with open(f'./db/data/users/{user_id}.json', 'r') as f:
            projects = json.load(f)
        return projects

    def save_user_projects(self, user_id, projects):
        with open(f'./db/data/users/{user_id}.json', 'w') as f:
            json.dump(projects, f)
        return True    

    
